package com.mofang.ticketing.common.web.core.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mofang.ticketing.common.core.exception.BizException;
import com.mofang.ticketing.common.core.result.Result;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Reader;
import java.nio.charset.Charset;


/**
 * feign 上游统一异常处理
 * Feign 在收到响应 HTTP 状态码为 40X、50X 等时会进入ErrorDecoder，我们可以自定义处理器：
 *
 * @author LGC
 */
@RequiredArgsConstructor
@Slf4j
public class FeignClientErrorDecoder implements ErrorDecoder {

    private final ObjectMapper objectMapper;

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            Reader reader = response.body().asReader(Charset.defaultCharset());
            Result<?> result = objectMapper.readValue(reader, Result.class);
            // 如果上游服务响应符合全局包装约定，再次抛出即可
            return new BizException(result.getCode(), result.getMsg());
        } catch (Exception e) {
            log.error("Response 转换异常: ", e);
            return new BizException("feign 服务调用异常");
        }
    }
}
